import datetime
import time

from django.http import JsonResponse
from rest_framework.views import APIView

from .serializers import *


#

def adds(func):
    def wrapper(request):

        try:
            print("auther is ok")
            token = request.COOKIES["token"]
            print(token)
            token = Token.objects.get(token=token)
            print(token.employee)
        except Exception as e:
            # raise exceptions.AuthenticationFailed('认证失败')
            return JsonResponse({"status": 1, "msg": "身份错误"})

        res = {"status": 0, "msg": "no", 'data': func(request)}
        response = JsonResponse(res)
        response["Access-Control-Allow-Origin"] = "http://localhost:8080"
        response["Cache-Control"] = "no-cache"
        response["Access-Control-Allow-Credentials"] = "true"
        response["Access-Control-Allow-Methods"] = "GET,POST"
        response["Access-Control-Allow-Headers"] = "Origin,Content-Type,Cookie,Accept,Token"
        return response

    return wrapper


def adds2(func):
    def wrapper(self, request):
        response = func(self, request)
        # response["Access-Control-Allow-Origin"] = "123"
        response["Access-Control-Allow-Origin"] = "http://localhost:8080"
        response["Cache-Control"] = "no-cache"
        response["Access-Control-Allow-Credentials"] = "true"
        response["Access-Control-Allow-Methods"] = "GET,POST"
        response["Access-Control-Allow-Headers"] = "Origin,Content-Type,Cookie,Accept,Token"
        print(dir(response))
        return response

    return wrapper


# Create your views here.

class Login(APIView):
    """
    登录使用
    """
    authentication_classes = []

    @adds2
    def get(self, request):
        print("this is login in get")
        ret = {"status": 0, "msg": "no error!"}
        user = None
        try:
            print(request.GET)
            print(request.data)
            user_name = request.GET["user_name"]
            password = request.GET["user_password"]
            print("name" + user_name)
            print("pas" + password)
            user = Employee.objects.get(name=user_name)
            print(user)
        except Exception as err:
            ret['status'] = "1"
            ret['msg'] = "没有找到用户"
            print(err)

        print(user)
        token = str(time.time()) + "username"
        Token.objects.update_or_create(employee=user, defaults={'token': token})
        ret['data'] = {
            "user_id": user.id,
            "user_name": user.name,
            "user_type": "employee"
        }

        ret = JsonResponse(ret)
        ret.set_cookie('token', token)
        request.session['token'] = token
        # print(r.COOKIES)
        return ret

    @adds2
    def post(self, request):
        print("this is login in post")
        token = request.COOKIES["token"]
        # token = request.session['token']
        print(token)
        token = Token.objects.get(token=token)
        print(token.employee)
        token.delete()
        ret = {"status": 0, "msg": "no error!"}
        return JsonResponse(ret)


class UserAPIView(APIView):
    """
        获取个人用户信息
    """
    @adds2
    def get(self, request):
        ret = {"status": 0, "msg": "no error!", "data": {}}
        token = request.COOKIES["token"]
        token = Token.objects.get(token=token)
        employee = token.employee
        print(employee)
        ret['data'] = {
            "user_id": employee.id,
            "user_name": employee.name,
            "user_type": "employee",
            "user_age": employee.age,
            "user_phone_number": employee.phone,
            "user_department_id": employee.department_id
        }
        return JsonResponse(ret)


class DepartmentAPIView(APIView):
    """
    这里完成获取全部的部门信息的功能
    """

    @adds2
    def get(self, request):
        ret = {"status": 0, "msg": "no error!", "data": []}
        departments = Department.objects.all()
        for department in departments:
            ret['data'].append({
                "department_id": department.supervisor_id,
                "department_name": department.name
            })
        return JsonResponse(ret)


"""
【测试】下面完成一些请假事项
"""


@adds
def leave_user(request):
    res = {"leave_all": []}
    user_id = request.GET.get("user_id")
    print(user_id)
    leaves = Leave.objects.filter(user_id=user_id)
    for leave in leaves:
        print(leave.start_time.__format__('%Y-%m-%d-%H-%M'))
        print(leave.end_time.__format__('%Y-%m-%d-%H-%M'))
        res["leave_all"].append({
            "start_time": leave.start_time.__format__('%Y-%m-%d-%H-%M'),
            "end_time": leave.end_time.__format__('%Y-%m-%d-%H-%M'),
            "leave_reason": leave.leave_reason,
            "leave_type": leave.leave_type,
            "leave_id": str(leave.leave_id),
            "leave_status": leave.leave_status,
            "user_id": leave.user_id,
            "user_name": "keven"
        })
    print(res)
    return res


@adds
def leave_id(request):
    leave = Leave.objects.get(leave_id=request.GET['leave_id'])
    print("This is leave id")

    print(type(leave.start_time))

    return {
        "start_time": leave.start_time.__format__('%Y-%m-%d-%H-%M'),
        "end_time": leave.end_time.__format__('%Y-%m-%d-%H-%M'),
        "leave_reason": leave.leave_reason,
        "leave_type": leave.leave_type,
        "leave_id": str(leave.leave_id),
        "leave_status": leave.leave_status,
        "user_id": leave.user_id,
        "user_name": "keven"
    }


@adds
def leave_application(request):
    print("this is application")
    print(request.POST)
    print(request.POST['start_time'])

    leave = Leave(
        user_id=request.POST.get('user_id'),
        start_time=datetime.datetime.strptime(request.POST.get('start_time'), '%Y-%m-%d-%H-%M'),
        end_time=datetime.datetime.strptime(request.POST.get('end_time'), '%Y-%m-%d-%H-%M'),
        leave_reason=request.POST.get('leave_reason'),
        leave_type=request.POST.get('leave_type'),
        leave_status="1",
    )

    leave.save()

    print(Leave.objects.all())
    return {}


@adds
def leave_all(request):
    print("this is leave all")
    print(request.POST)

    res = {"leave_all": []}

    leaves = Leave.objects.all()
    print(Leave.objects.all())
    print(leaves)
    for leave in leaves:
        print(leave.start_time.__format__('%Y-%m-%d-%H-%M'))
        print(leave.end_time.__format__('%Y-%m-%d-%H-%M'))
        res["leave_all"].append({
            "start_time": leave.start_time.__format__('%Y-%m-%d-%H-%M'),
            "end_time": leave.end_time.__format__('%Y-%m-%d-%H-%M'),
            "leave_reason": leave.leave_reason,
            "leave_type": leave.leave_type,
            "leave_id": str(leave.leave_id),
            "leave_status": leave.leave_status,
            "user_id": leave.user_id,
            "user_name": "keven"
        })
    print(res)
    print("ok")
    return res


@adds
def leave_manager_agreement(request):
    print("leave_manager_agreement")
    leave_id = request.POST['leave_id']
    leave = Leave.objects.get(leave_id=leave_id)
    leave.leave_status = "2"
    leave.save()
    return {}


@adds
def leave_manager_disagreement(request):
    print("leave_manager_agreement")
    leave_id = request.POST['leave_id']
    leave = Leave.objects.get(leave_id=leave_id)
    leave.leave_status = "3"
    leave.save()
    return {}


@adds
def leave_employee_agreement(request):
    print("leave_manager_agreement")
    leave_id = request.POST['leave_id']
    leave = Leave.objects.get(leave_id=leave_id)
    leave.leave_status = "4"
    leave.save()
    return {}


@adds
def leave_employee_disagreement(request):
    print("leave_manager_agreement")
    leave_id = request.POST['leave_id']
    leave = Leave.objects.get(leave_id=leave_id)
    leave.leave_status = "5"
    leave.save()
    return {}
